from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from artmarket.models import Order
from artmarket.serializers import OrderSerializer


class AdminOrderListView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取所有订单（包括退货申请中的订单）
        orders = Order.objects.all()
        serializer = OrderSerializer(instance=orders, many=True)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)


class AdminOrderApprovalView(APIView):
    permission_classes = [IsAdminUser]

    def post(self, request, pk, action):
        order = get_object_or_404(Order, pk=pk)

        if action == '1':
            if order.status == Order.ORDER_RETURN_REQUESTED:
                order.status = Order.ORDER_RETURN_APPROVED
                order.save()
                # 将艺术品重新分配给原始艺术家
                artwork = order.artwork
                original_artist = order.original_artist
                if original_artist:
                    artwork.artist = original_artist
                    artwork.save()
                return Response({'message': '退货申请已批准'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '无效操作'}, status=status.HTTP_400_BAD_REQUEST)
        elif action == '0':
            if order.status == Order.ORDER_RETURN_REQUESTED:
                order.status = Order.ORDER_RETURN_REJECTED
                order.save()
                return Response({'message': '退货申请已拒绝'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '无效操作'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'error': '无效操作'}, status=status.HTTP_400_BAD_REQUEST)